#!/bin/bash

# $Header$
# Author: yang.jin@ebay.com

export PATH=/bin:/usr/bin:/sbin:/usr/sbin:/opt/bind/bin:/opt/bind/sbin
BINDDIR="/opt/bind"

if [ $# -ne 1 ]; then 
	echo "
		$(basename $0) - use another set of BIND binaries for a DNS server

		Usage:
			
		$(basename $0) release 
"
	exit 1	
fi

release=$1

if [ "X$(uname -s)" == "XSunOS" ]; then
	GREP="/usr/xpg4/bin/grep"
	START="svcadm enable dns/server"
	STOP="svcadm disable dns/server"
else
	GREP="/bin/grep"
	START="service named start"
	STOP="service named stop"
fi

echo -e "\nVerifying ${BINDDIR}-${release}/sbin/named...\t\c"
if [ -x ${BINDDIR}-${release}/sbin/named ]; then echo Passed; else echo Failed; exit 1; fi

echo -e "Checking named is running...\t\t\t\c"
if [ "X$(pgrep named)" != "X" ]; then 
	echo Yes
	echo -e "Checking original named version...\t\t\c"
	running=$(rndc status | grep ^version: | sed -e "s/version://" -e "s/BIND//" | awk '{print $1}')
	echo $running
else
	echo No
fi

if [ "X${release}" == "X${running}" ]; then
	echo "BIND $release is running. Cutover is skipped."
	exit 0
fi

if [ "X$(pgrep named)" != "X" ]; then
	echo -e "Shutting down named...\t\t\t\t\c"
	$STOP >/dev/null
	if [ $? -eq 0 ]; then echo Succeeded; else echo Failed; fi
	while [ "X$(pgrep named)" != "X" ]; do sleep 2; done
fi

echo -e "Unlinking ${BINDDIR}...\t\t\t\t\c"
if [ -L $BINDDIR ]; then
	unlink $BINDDIR
	if [ $? -eq 0 ]; then echo Succeeded; else echo Failed; fi
else
	echo Skipped
fi

echo -e "Creating a symbolic link ${BINDDIR}...\t\t\c"
ln -s ${BINDDIR}-${release} $BINDDIR
if [ $? -eq 0 ]; then echo Succeeded; else echo Failed; fi

echo -e "Bringing up named...\t\t\t\t\c"
$START >/dev/null
if [ $? -eq 0 ]; then echo Succeeded; else echo Failed; exit 9; fi
if [ "X$(uname -s)" == "XSunOS" ]; then
	echo -e "Pending on named being started...\t\t\c"
	while [ $(pgrep named | wc -l) -ne 1 ]; do sleep 2; done
	echo Completed
fi

echo -e "Checking running named version...\t\t\c"
rndc status | grep ^version: | sed -e "s/version://" -e "s/BIND//" | awk '{print $1}'
echo
